/*
 * Filename: NetworkService.java
 * Description: This class provides all related functions about network connectivity. 
 */

package edu.usc.libtalk.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import android.widget.Toast;

public class NetworkService extends Application implements InternalConstant{

	private static Context context;
	private static ConnectivityManager connectionManager;
	private static final String TAG = "NetworkService";

	public static Activity register(Activity activity){
		
		if(context == null){
			context = activity.getApplicationContext();
		}
		
		return activity;
	}	
	
	@Override
	public void onCreate() {
		
		context = getApplicationContext();
		connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	}
	
	public static boolean hasInternetConnection() {		
		return connectionManager != null 
				&& connectionManager.getActiveNetworkInfo() != null
				&& connectionManager.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	
	public static String executeHttpGet(String url) {
		BufferedReader in = null;

		if(!hasInternetConnection()) {
			Log.e(TAG, "executeHttpGet: no the Internet connection");
			return null;
		}
		
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			
			HttpResponse response = client.execute(request);
			
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			
			return sb.toString();
			
		} catch(Exception e) { 
			 Log.e(TAG, "executeHttpGet: " + e.toString());
		}
		
		return null;
	}
	
	public static void inform(String message){
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}	
}
